<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户角色管理</title>
    <!-- 引入Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入Font Awesome图标 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .table-container {
            margin-top: 20px;
        }
        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: center;
        }
        .form-container {
            margin-bottom: 20px;
            padding: 20px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            background-color: #f8f9fa;
        }
        .action-buttons {
            white-space: nowrap;
        }
    </style>
</head>
<body>
<div class="container">
    <h2 class="my-4">用户角色管理</h2>

    <!-- 添加用户角色表单 -->
    <div class="form-container">
        <h4>添加用户角色</h4>
        <form id="addForm">
            <div class="row">
                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="userId" class="form-label">用户ID</label>
                        <input type="number" class="form-control" id="userId" name="userId" required>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="roleId" class="form-label">角色ID</label>
                        <input type="number" class="form-control" id="roleId" name="roleId" required>
                    </div>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary">添加</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 搜索和分页控制 -->
    <div class="row mb-3">
        <div class="col-md-3">
            <input type="number" class="form-control" id="searchUserId" placeholder="按用户ID搜索">
        </div>
        <div class="col-md-3">
            <input type="number" class="form-control" id="searchRoleId" placeholder="按角色ID搜索">
        </div>
        <div class="col-md-2">
            <button class="btn btn-outline-secondary" id="searchBtn">搜索</button>
            <button class="btn btn-outline-secondary" id="resetBtn">重置</button>
        </div>
    </div>

    <!-- 用户角色表格 -->
    <div class="table-container">
        <table class="table table-striped table-hover">
            <thead>
            <tr>
                <th>ID</th>
                <th>用户ID</th>
                <th>角色ID</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="dataTable">
            <!-- 数据将通过Ajax动态加载 -->
            </tbody>
        </table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
        <nav aria-label="Page navigation">
            <ul class="pagination" id="pagination">
                <!-- 分页将通过Ajax动态生成 -->
            </ul>
        </nav>
    </div>

    <!-- 修改模态框 -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">修改用户角色</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editForm">
                        <input type="hidden" id="editId" name="id">
                        <div class="mb-3">
                            <label for="editUserId" class="form-label">用户ID</label>
                            <input type="number" class="form-control" id="editUserId" name="userId" required>
                        </div>
                        <div class="mb-3">
                            <label for="editRoleId" class="form-label">角色ID</label>
                            <input type="number" class="form-control" id="editRoleId" name="roleId" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveEditBtn">保存</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 引入jQuery和Bootstrap JS -->
<script src="js/jquery-3.6.0.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>

<script>
    $(document).ready(function() {
        let currentPage = 1;
        const pageSize = 10;

        // 初始化页面
        loadData();

        // 添加用户角色
        $('#addForm').submit(function(e) {
            e.preventDefault();
            const formData = {
                userId: $('#userId').val(),
                roleId: $('#roleId').val()
            };

            $.ajax({
                url: '/sysUserRole/addSysUserRole',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    if (response.msg === 'success') {
                        alert('添加成功');
                        $('#addForm')[0].reset();
                        loadData();
                    } else {
                        alert('添加失败: ' + (response.error || '未知错误'));
                    }
                },
                error: function(xhr) {
                    alert('请求失败: ' + xhr.statusText);
                }
            });
        });

        // 搜索
        $('#searchBtn').click(function() {
            currentPage = 1;
            loadData();
        });

        // 重置搜索
        $('#resetBtn').click(function() {
            $('#searchUserId').val('');
            $('#searchRoleId').val('');
            currentPage = 1;
            loadData();
        });

        // 加载数据
        function loadData() {
            const userId = $('#searchUserId').val();
            const roleId = $('#searchRoleId').val();

            $.ajax({
                url: '/sysUserRole/pageSysUserRole',
                type: 'GET',
                data: {
                    userId: userId,
                    roleId: roleId,
                    current: currentPage,
                    pageSize: pageSize
                },
                success: function(response) {
                    renderTable(response.records);
                    renderPagination(response.total, response.pages);
                },
                error: function(xhr) {
                    alert('加载数据失败: ' + xhr.statusText);
                }
            });
        }

        // 渲染表格数据
        function renderTable(data) {
            const $tableBody = $('#dataTable');
            $tableBody.empty();

            if (data.length === 0) {
                $tableBody.append('<tr><td colspan="4" class="text-center">暂无数据</td></tr>');
                return;
            }

            data.forEach(item => {
                const row = `
                        <tr>
                            <td>${item.id}</td>
                            <td>${item.userId}</td>
                            <td>${item.roleId}</td>
                            <td class="action-buttons">
                                <button class="btn btn-sm btn-warning edit-btn" data-id="${item.id}">
                                    <i class="fas fa-edit"></i> 修改
                                </button>
                                <button class="btn btn-sm btn-danger delete-btn" data-id="${item.id}">
                                    <i class="fas fa-trash-alt"></i> 删除
                                </button>
                            </td>
                        </tr>
                    `;
                $tableBody.append(row);
            });

            // 绑定编辑按钮事件
            $('.edit-btn').click(function() {
                const id = $(this).data('id');
                editUserRole(id);
            });

            // 绑定删除按钮事件
            $('.delete-btn').click(function() {
                const id = $(this).data('id');
                deleteUserRole(id);
            });
        }

        // 渲染分页
        function renderPagination(total, pages) {
            const $pagination = $('#pagination');
            $pagination.empty();

            if (pages <= 1) return;

            // 上一页
            $pagination.append(`
                    <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                        <a class="page-link" href="#" aria-label="Previous" data-page="${currentPage - 1}">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                `);

            // 页码
            for (let i = 1; i <= pages; i++) {
                $pagination.append(`
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" data-page="${i}">${i}</a>
                        </li>
                    `);
            }

            // 下一页
            $pagination.append(`
                    <li class="page-item ${currentPage === pages ? 'disabled' : ''}">
                        <a class="page-link" href="#" aria-label="Next" data-page="${currentPage + 1}">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                `);

            // 绑定分页点击事件
            $('.page-link').click(function(e) {
                e.preventDefault();
                const page = $(this).data('page');
                if (page && page !== currentPage) {
                    currentPage = page;
                    loadData();
                }
            });
        }

        // 编辑用户角色
        function editUserRole(id) {
            $.ajax({
                url: '/sysUserRole/' + id,
                type: 'GET',
                success: function(data) {
                    $('#editId').val(data.id);
                    $('#editUserId').val(data.userId);
                    $('#editRoleId').val(data.roleId);

                    const editModal = new bootstrap.Modal(document.getElementById('editModal'));
                    editModal.show();
                },
                error: function(xhr) {
                    alert('获取数据失败: ' + xhr.statusText);
                }
            });
        }

        // 保存编辑
        $('#saveEditBtn').click(function() {
            const formData = {
                id: $('#editId').val(),
                userId: parseInt($('#editUserId').val(), 10),
                roleId: parseInt($('#editRoleId').val(), 10)
            };

            $.ajax({
                url: '/sysUserRole/updateSysUserRole',
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    if (response.msg == 'success') {
                        alert('修改成功');
                        $('#editModal').modal('hide');
                        loadData();
                    } else {
                        alert('修改失败: ' + (response.error || '未知错误'));
                    }
                },
                error: function(xhr) {
                    alert('请求失败: ' + xhr.statusText);
                }
            });
        });

        // 删除用户角色
        function deleteUserRole(id) {
            if (!confirm('确定要删除这条记录吗？')) return;

            $.ajax({
                url: '/sysUserRole/deleteSysUserRole?id=' + id,
                type: 'DELETE',
                success: function(response) {
                    if (response.msg === 'success') {
                        alert('删除成功');
                        loadData();
                    } else {
                        alert('删除失败: ' + (response.error || '未知错误'));
                    }
                },
                error: function(xhr) {
                    alert('请求失败: ' + xhr.statusText);
                }
            });
        }
    });
</script>
</body>
</html>